package com.liang.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.liang.entity.User;
import com.liang.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/*
 *@Author: ljy
 *@Date:2021/11/6 11:45
 *
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 导出Excel
     * @param response
     * @throws IOException
     */
    @RequestMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        //查询数据库所有数据
        List<User> users=userService.findAll();
        log.info("导出Excel,当前数据库中的数据总数为：[{}]",users.size());
        //生成excel
        /**
         * sheet名字，excel标题 作为参数进入new  ExportParams（）
         */
        Workbook workbook= ExcelExportUtil.exportExcel(new ExportParams("用户标题信息","用户信息"),User.class,users);
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode("用户列表.xls","UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }
}
